//
//  LSPictureSelectorController.swift
//  PictureSelector
//
//  Created by lj on 15/9/11.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let LSPictureSelectorControllerID = "LSPictureSelectorControllerID"

/// 最大图片数
private let kLSMaxPictureCount = 9


class LSPictureSelectorController: UICollectionViewController,LSPictureSelectorCellDelegate {

    /// 照片数组 - 数据源
    var pictures = [UIImage]()
    /// 当前选中的照片的索引
    private var currentIndex = 0
    
    //MARK: -界面搭建
//    override init(collectionViewLayout layout: UICollectionViewLayout) {
//        super.init(collectionViewLayout: UICollectionViewFlowLayout())
//    }
    
    init() {
        let layout = UICollectionViewFlowLayout()
        
        super.init(collectionViewLayout: layout)
        
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView?.registerClass(LSPictureSelectorCell.self, forCellWithReuseIdentifier: LSPictureSelectorControllerID)

        collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
    }

    // MARK:- UICollectionViewDataSource
   override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    return pictures.count + (pictures.count == kLSMaxPictureCount ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LSPictureSelectorControllerID, forIndexPath: indexPath) as! LSPictureSelectorCell
        
        //设置代理
        cell.pictureDelegate = self
        
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        
        return cell
    }
    
    
    //MARK: LSPictureSelectorCellDelegate
    /// 添加图片
    private func pictureSelectorCellClickedPictureButton(cell: LSPictureSelectorCell) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("无法访问相册")
            return
        }
        //当前cell的标记
        currentIndex = (collectionView?.indexPathForCell(cell)?.item)!
        
        //
        let viewController = UIImagePickerController()
        
        //监听照片选择
        viewController.delegate = self
        
        presentViewController(viewController, animated: true, completion: nil)
        
    }
    
    /// 删除对应的图片
    private func picturSelectorCellClickedRemoveButton(cell: LSPictureSelectorCell) {

//        print(collectionView?.indexPathForCell(cell)?.item)
        
        pictures.removeAtIndex((collectionView?.indexPathForCell(cell)?.item)!)
        
        collectionView?.reloadData()
        
    }

}

//MARK:- UIImagePickerControllerDelegate,UINavigationControllerDelegate

extension LSPictureSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        if currentIndex < pictures.count {
            
            pictures[currentIndex] = image
        } else {
            pictures.append(image)
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}


//MARK:- 

/// 声明照片cell协议
private protocol LSPictureSelectorCellDelegate:NSObjectProtocol {
    
    func pictureSelectorCellClickedPictureButton(cell:LSPictureSelectorCell)
    
    func picturSelectorCellClickedRemoveButton(cell:LSPictureSelectorCell)
}

private class LSPictureSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            if image != nil {
            
                pictureButton.setImage(image, forState: UIControlState.Normal)
            } else {
                pictureButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            }
            removeButton.hidden = (image == nil)
        }
        
    }
    
    /// 定义代理
    weak var pictureDelegate: LSPictureSelectorCellDelegate?
    
    /// pictureButtonClicked
    @objc private func pictureButtonClicked() {
        
        pictureDelegate?.pictureSelectorCellClickedPictureButton(self)
    }
    
    /// 删除按钮点击事件
    @objc private func removeButtonClicked() {
    
        pictureDelegate?.picturSelectorCellClickedRemoveButton(self)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI
    /// 设置UI
    private func setupUI() {
        //添加控件
        contentView.addSubview(pictureButton)
        contentView.addSubview(removeButton)
        
        //设置自动布局
        
        pictureButton.frame = bounds
//        pictureButton.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraint(NSLayoutConstraint(item: pictureButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: pictureButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: pictureButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: pictureButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
        
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
       
        //监听按钮点击
        pictureButton.addTarget(self, action: "pictureButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "removeButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    /// 懒加载控件
    private lazy var pictureButton:UIButton = UIButton(imageName: "compose_pic_add")
    
    private lazy var removeButton:UIButton = UIButton(imageName: "compose_photo_close")
    
}

